<template>
  <div>
<van-nav-bar
  title="登录"
  left-arrow
  @click-left="$router.back()"
/>

<!-- 表单 -->
    <van-form  @submit="onSubmit">
        <van-field
            v-model="username"
            name="username"
            label="手机号"
            placeholder="请填写手机号"
            :rules="[{ required: true, message: '请填写手机号' },{pattern:/^1[3-9]\d{9}$/,message:'手机格式错误'}]"
        />

       <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { validator: (e)=> /^\w{6,12}$/.test(e), message: '密码格式错误' },
        ]"
      />


    <div style="margin: 16px;">
        <van-button block type="info" color='#07c160' native-type="submit">提交</van-button>
    </div>

    <div>
        <router-link to="/reg">去注册</router-link>
    </div>
</van-form>

  </div>
</template>

<script>

import { Form } from 'vant';
import { Field } from 'vant';
import {login} from '@/api/user'


export default {
    name:'login',
    data(){
        return{
            username:'',
            password:'',
            
        }
    },
    components: {
        [Form.name]:Form,
        [Field.name]:Field,
       
    },
    mounted(){
        
    },
    methods:{
        onSubmit(values) {
      console.log('submit', values);

      login(values).then(res=>{
        console.log(res)

        if(res.code==0){

          let {token,uid,userInfo} = res;
          localStorage.setItem('token',token)
          localStorage.setItem('uid',uid)
          localStorage.setItem('userInfo',JSON.stringify(userInfo))

          this.$store.commit('change',{key:'uid',value:uid})
          this.$store.commit('change',{key:'token',value:token})
          this.$store.commit('change',{key:'userInfo',value:userInfo})
          this.$store.commit('change',{key:'isLogin',value:true})

          setTimeout(v=>{
            this.$router.back()
          },500)

        }else{
            this.$toast(res.msg || '登录失败')
        }
      })
    },
    
    }
}
</script>

<style lang="less">
    
</style>